package alibaba.java8datetimeapi;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author ChangLiang
 * @date 2020/4/17
 */
public class SimpleDateFormatTest {

    /**
     * define a global SimpleDateFormat
     */
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * use threadFactoryBuilder to define a thread pool
     */
    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();


    private static ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    private static CountDownLatch countDownLatch = new CountDownLatch(100);

    @Test
    public void test1() throws InterruptedException {

        Set<String> dates = Collections.synchronizedSet(new HashSet<>());
        for (int i = 0; i < 100; i++) {
            Calendar calendar = Calendar.getInstance();
            int finalI = i;
            pool.execute(()->{
                // add finalI days to the calendar
                calendar.add(Calendar.DATE,finalI);
                // Thread 1 2019-06-28 + 1
                // Thread 2 2019-06-28 + 2
                // Thread 3 2019-06-28 + 3
                // before thread 1 simpleDateFormat finished
                // thread 2 finished so SimpleDateFormat‘s inner calendar property changed
                // so thread 2 = 2019-06-30
                // so thread 3 = 2019-06-31
                // so thread 1 = 2019-06-31 and skip and 2019-06-29 missing
                String dateString = simpleDateFormat.format(calendar.getTime());
                dates.add(dateString);
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println(dates.size());

        ArrayList list = Util.convertToSortedArrayList(dates);
        System.out.println(list);
    }


}
